﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using C.Unite;
using C.Entities;
using ChanExt;
using MySoft.Data;
using System.Text;
using LitJson;
using System.Data;
using Newtonsoft.Json.Linq;

namespace ArtLand.OA.Project.Project
{
    public partial class Pro_PoDataList : CommonPageBase
    {


        public string t = "";
        /// <summary>
        /// 取得权限
        /// </summary>
        /// <returns></returns>
        public bool GetQX()
        {

            bool n = true;
            string UserKeys = UserPower.GetHaveKey();
            if (!UserKeys.Contains("View"))
            {
                PageContext.RegisterStartupScript("alert('您未有查看权限！');RemTab('dynamic_added_tab_tab_" + UserPower.GetKeyWord() + "');");
                n = false;
            }
            else
            {
                if (!UserKeys.Contains("Audit"))
                {
                    Grid1.Columns[Grid1.Columns.Count - 1].Hidden = true;
                }
            }
            return n;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (GetQX())
                {
                    btnNew.OnClientClick = Window1.GetShowReference("Pro_PoDataChange.aspx", "新增采购订单");

                    BindGrid(GetWhere());

                    string sql = "";
                    if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
                    {
                        sql += " and (b.CONNUB like '%" + ttbxMyBox2.Text + "%' or b.PONBER like '%" + ttbxMyBox2.Text + "%')";// wc = wc && (Proj_Podata._.CONNUB.Contain(ttbxMyBox2.Text) || Proj_Podata._.PONBER.Contain(ttbxMyBox2.Text));
                    }
                    if (!string.IsNullOrEmpty(Request["cid"]))
                    {
                        Proj_Contat pc = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.ID == int.Parse(Request["cid"])).ToFirst();
                        sql += " and b.CONNUB='" + pc.CONNUB + "'";
                    }
                    if (txt_StartTime.Text != "")
                    {
                        sql += " and b.DLDATE>'" + txt_StartTime.Text + "'";
                    }
                    if (txt_EndTime.Text != "")
                        sql += " and b.DLDATE<'" + txt_EndTime.Text + "'";
                    if (txt_VEDNUB.Text != "")
                        sql += " and b.VEDNUB like '%" + txt_VEDNUB.Text + "%'";
                    if (txt_CONNUB.Text != "")
                        sql += " and b.CONNUB like '%" + txt_CONNUB.Text + "%'";


                    decimal d = TbsDbSession.Default.From<Proj_Podata>().Select(Proj_Podata._.TAMOUT.Sum()).Where(Proj_Podata._.STATUS == 1 && GetWhere()).ToScalar<decimal>();
                    decimal p = TbsDbSession.Default.FromSql("select sum(remout) from Proj_Popayf a,Proj_Podata b where a.ponubr=b.ponber and status=1 " + sql).ToScalar<decimal>(); //TbsDbSession.Default.From<Proj_Popayf>().Select(Proj_Popayf._.REMOUT.Sum()).ToScalar<decimal>();


                    ToolbarText2.Text = "<b>订单未付金额:<font color='red'>" + Math.Round(d - p, 2) + "</font></b>";
                    OutputSummaryData(true);
                }
            }
        }

        private void OutputSummaryData(bool tt)
        {

            string sql = "";
            if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
            {
                sql += " and (b.CONNUB like '%" + ttbxMyBox2.Text + "%' or b.PONBER like '%" + ttbxMyBox2.Text + "%')";// wc = wc && (Proj_Podata._.CONNUB.Contain(ttbxMyBox2.Text) || Proj_Podata._.PONBER.Contain(ttbxMyBox2.Text));
            }
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                Proj_Contat pc = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.ID == int.Parse(Request["cid"])).ToFirst();
                sql += " and b.CONNUB='" + pc.CONNUB + "'";
            }
            if (txt_StartTime.Text != "")
            {
                sql += " and b.DLDATE>'" + txt_StartTime.Text + "'";
            }
            if (txt_EndTime.Text != "")
                sql += " and b.DLDATE<'" + txt_EndTime.Text + "'";
            if (txt_VEDNUB.Text != "")
                sql += " and b.VEDNUB like '%" + txt_VEDNUB.Text + "%'";
            if (txt_CONNUB.Text != "")
                sql += " and b.CONNUB like '%" + txt_CONNUB.Text + "%'";

            decimal d = TbsDbSession.Default.From<Proj_Podata>().Select(Proj_Podata._.TAMOUT.Sum()).Where(Proj_Podata._.STATUS == 1 && GetWhere()).ToScalar<decimal>();
            decimal p = TbsDbSession.Default.FromSql("select sum(remout) from Proj_Popayf a,Proj_Podata b where a.ponubr=b.ponber and status=1 " + sql + "").ToScalar<decimal>(); //TbsDbSession.Default.From<Proj_Popayf>().Select(Proj_Popayf._.REMOUT.Sum()).ToScalar<decimal>();



            //float donateTotal = 0.0f;
            //float feeTotal = 0.0f;
            //foreach (DataRow row in source.Rows)
            //{
            //    donateTotal += Convert.ToInt32(row["Donate"]);
            //    feeTotal += Convert.ToInt32(row["Fee"]);
            //}
            //donateTotal = float.Parse(d.ToString());
            //feeTotal = float.Parse((d - p).ToString());
            JObject jo = new JObject();
            jo.Add("donateTotal", d);
            jo.Add("feeTotal", d - p);

            t = jo.ToString(Newtonsoft.Json.Formatting.None);
            if (tt == false)
                PageContext.RegisterStartupScript("customsummary('" + t + "','" + Grid1.ClientID + "')");
        }



        #region BindGrid
        private void BindGrid(WhereClip wc)
        {
            Grid1.RecordCount = TbsDbSession.Default.From<Proj_Podata>().Where(wc).Count();

            List<Proj_Podata> items = TbsDbSession.Default.From<Proj_Podata>().Where(wc).OrderBy(Proj_Podata._.ID.Desc).Page(Grid1.PageSize, (Grid1.PageIndex + 1)).ToList();
            Cache.Insert("podata_" + CookInfo.EAdminid(), items);
            // 3.绑定到Grid
            Grid1.DataSource = items;
            Grid1.DataBind();
        }



        protected void Grid1_PageIndexChange(object sender, ChanExt.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid(GetWhere());
        }

        public WhereClip GetWhere()
        {
            WhereClip wc = WhereClip.All;
            //if (!string.IsNullOrEmpty(Request["did"]))
            //{
            //    wc = wc && Adm_BASICD._.BATYPE == int.Parse(Request["did"]);
            //}
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                Proj_Contat pc = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.ID == int.Parse(Request["cid"])).ToFirst();
                wc = wc && Proj_Podata._.CONNUB == pc.CONNUB;
            }
            if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
            {
                wc = wc && (Proj_Podata._.CONNUB.Contain(ttbxMyBox2.Text) || Proj_Podata._.PONBER.Contain(ttbxMyBox2.Text));
            }

            if (txt_StartTime.Text != "")
            {
                wc = wc && Proj_Podata._.DLDATE > txt_StartTime.Text;
            }
            if (txt_EndTime.Text != "")
                wc = wc && Proj_Podata._.DLDATE < txt_EndTime.Text;
            if (txt_VEDNUB.Text != "")
                wc = wc && Proj_Podata._.VEDNUB.Contain(txt_VEDNUB.Text);
            if (txt_CONNUB.Text != "")
                wc = wc && Proj_Podata._.CONNUB.Contain(txt_CONNUB.Text);


            if (!string.IsNullOrEmpty(Request["t"]))
            {

                List<VI_C3> listc = TbsDbSession.Default.From<VI_C3>().Where(VI_C3._.C == 1).ToList();
                int[] listint = (from p in listc select p.ID).ToArray();
                if (listint.Length > 0)
                    wc = wc && Proj_Podata._.ID.SelectIn<int>(listint);
                else
                {
                    PageContext.RegisterStartupScript("top.__doPostBack('hid_btn', '');top.RemoveT('M_waitauditorder_x');");
                }
            }
            if (!string.IsNullOrEmpty(Request["m"]))
            {
                List<VI_C4> listc = TbsDbSession.Default.From<VI_C4>().Where(VI_C4._.C == 1).ToList();
                int[] listint = (from p in listc select p.ID).ToArray();
                if (listint.Length > 0)
                    wc = wc && Proj_Podata._.ID.SelectIn<int>(listint);
                else
                {
                    PageContext.RegisterStartupScript("top.__doPostBack('hid_btn', '');top.RemoveT('M_waitshou_x');");
                }
            }

            return wc;
        }
        // 点击 TwinTriggerBox 的搜索按钮
        protected void ttbxMyBox2_Trigger2Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
            {
                // 执行搜索动作
                BindGrid(GetWhere());
                OutputSummaryData(false);
                ttbxMyBox2.ShowTrigger1 = true;
            }
            else
            {
                Alert.ShowInTop("请输入你要搜索的关键词！");
            }
        }

        // 点击 TwinTriggerBox 的取消按钮
        protected void ttbxMyBox2_Trigger1Click(object sender, EventArgs e)
        {
            // 执行清空动作

            ttbxMyBox2.Text = "";
            ttbxMyBox2.ShowTrigger1 = false;
            BindGrid(GetWhere());
            OutputSummaryData(false);
        }
        #endregion

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            string s = e.Values[12].ToString().Trim();
            if (s == "0")
            {
                s = "未审批";
            }
            else
            {
                if (s == "1")
                {
                    s = "已审批";
                    e.Values[15] = s;
                }
                else
                {
                    s = "审批拒绝";
                    e.Values[15] = s;
                }
            }
            e.Values[12] = s;

            string pono = e.Values[0].ToString();
            string id = e.Values[7].ToString();
            decimal z = decimal.Parse(e.Values[6].ToString());
            decimal j = 0;
            List<Proj_Popayf> popayfList = TbsDbSession.Default.From<Proj_Popayf>().Where(Proj_Popayf._.PONUBR == pono).ToList();
            foreach (Proj_Popayf item in popayfList)
            {
                j += item.REMOUT.Value;
            }
            decimal y = z - j;
            e.Values[7] = "<a href=\"javascript:;\" onclick=\"TabView('/Project/Pro_PopayfList.aspx?pid=" + id + "', 'tab_wxaddasdf123f', '查看订单付款记录', '');\">" + y.ToString() + "</a>";



            string n = e.Values[5].ToString();
            Proj_Vendor ven = TbsDbSession.Default.From<Proj_Vendor>().Where(Proj_Vendor._.VEDNUB == n).ToFirst();
            if (ven != null)
            {
                if (ven.EasyName != null && ven.EasyName != "")
                    e.Values[5] = ven.EasyName;
                else
                    e.Values[5] = "暂未设定";
            }
            //string color = e.Values[7].ToString();
            //string bold = e.Values[8].ToString();
            //if (bold == "True")
            //    bold = "bold";
            //else
            //    bold = "";
            //string title = "<span style=\"color:{0};font-weight:{1}\">" + e.Values[0] + "</span>";
            //title = string.Format(title, color, bold);
            //e.Values[0] = title;
            //e.Values[7] = "<a href=\"javascript:;\" onclick=\"TabView('/AfterSale/ASale_RePairChange.aspx?id=" + e.Values[7] + "', 'tab_wxadd', '修改维修记录', '/icon/comment_edit.png');\"><img src=\"/icon/comment_edit.png\" /></a>";
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());
            if (e.CommandName == "Del")
            {
                TbsDbSession.Default.Delete<Proj_Podata>(Proj_Podata._.ID == id);
                Alert.ShowInTop("删除成功！");
                BindGrid(GetWhere());
            }
            if (e.CommandName == "CheckBox1")
            {
                CheckBoxField checkField = (CheckBoxField)Grid1.FindColumn(e.ColumnIndex);
                bool checkState = checkField.GetCheckedState(e.RowIndex);
                Proj_Podata tea = new Proj_Podata();
                tea.ID = id;
                tea.Attach();
                tea.IsShou = checkState;
                TbsDbSession.Default.Update<Proj_Podata>(tea);
                BindGrid(GetWhere());
            }


        }

        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {

            int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());
            string s = Grid1.DataKeys[e.RowIndex][1].ToString();
            if (s == "0")
                PageContext.RegisterStartupScript(Window1.GetShowReference("Pro_PopayfChange.aspx?pid=" + id, "修改采购付款记录"));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            FormInfo.GridEdit(Grid1, Window1, "Pro_PoDataChange.aspx");
            BindGrid(GetWhere());
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            FormInfo.GridDelete<Proj_Podata>(Grid1, Window1, new Proj_Podata());
            BindGrid(GetWhere());
        }

        protected void btnContatAdd_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "添加项目合同";
            FormInfo.GridEdit(Grid1, Window2, "Pro_ContatChange.aspx", wa, "cid");
        }


        protected void btnView_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_ContatList.aspx", "pid", "/icon/icon-form-search.gif", "查看相关合同");
        }

        protected void btnMoneyAdd_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "新增采购付款记录";
            FormInfo.GridEdit(Grid1, Window1, "Pro_PopayfChange.aspx", wa, "pid");
        }

        protected void btnMoneyView_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_PopayfList.aspx", "pid", "/icon/application-list.png", "查看采购付款记录");
        }

        protected void Grid1_RowSelect(object sender, GridRowSelectEventArgs e)
        {
            int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());
            string s = Grid1.DataKeys[e.RowIndex][1].ToString();
            if (s == "0")
            {
                Button1.Enabled = true;
                Button2.Enabled = true;
            }
            else
            {
                // Button1.Enabled = false;
                Button2.Enabled = false;
            }
        }

        protected void btn_Search_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window3.GetShowReference());
        }

        protected void btn_Pring_Click(object sender, EventArgs e)
        {

        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            BindGrid(GetWhere());
            PageContext.RegisterStartupScript(Window3.GetHideReference());
            OutputSummaryData(false);
        }

        protected void MenuButton1_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "新增运货计划";
            FormInfo.GridEdit(Grid1, Window4, "Pro_DeliveryChange.aspx", wa, "pid");
        }

        protected void MenuButton2_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_DeliveryList.aspx", "pid", "/icon/lorry_go.png", "查看送货计划记录");
        }

    }
}